package com.wenhai.spring.questions;

import com.wenhai.xiaomage.spring.ioc.overview.dependency.domain.User;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;

/**
 * {@link ObjectFactory} 延迟依赖查找
 *
 * @author wenhai
 * @date   2021/4/13
 * @see ObjectFactory
 * @see ObjectProvider
 */
public class ObjectFactoryLazyLookupDemo {
    public static void main(String[] args) {
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
        context.register(ObjectFactoryLazyLookupDemo.class);
        context.refresh();
        ObjectFactoryLazyLookupDemo objectFactoryLazyLookupDemo = context.getBean(ObjectFactoryLazyLookupDemo.class);
        ObjectFactory<User> objectFactory = objectFactoryLazyLookupDemo.objectFactory;
        ObjectFactory<User> objectProvider = objectFactoryLazyLookupDemo.objectProvider;
        System.out.println("userObjectProvider == userObjectFactory:" + (objectFactory == objectProvider));
        System.out.println("userObjectProvider.getClass == userObjectFactory.getClass:" + (objectFactory.getClass() == objectProvider.getClass()));
        System.out.println(objectFactory.getObject());
        context.close();

    }

    @Autowired
    private ObjectFactory<User> objectFactory;

    @Autowired
    private ObjectProvider<User> objectProvider;

    @Bean
    @Scope(AbstractBeanDefinition.SCOPE_PROTOTYPE)
    public static User user() {
        User user = new User();
        user.setId(1L);
        user.setUsername("文海");
        return user;
    }
}
